package cn.edu.zut.salarymanagesystem.utils;

import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Log;

import java.util.Arrays;

import javax.crypto.Cipher;

/**
 * 获取当前APK的版本号和版本名
 */
public class APKVersionInfoUtils {

    /**
     * 获取当前apk的版本号
     *
     * @param mContext
     * @return
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("d8g", "GetVersionCode Error!:" + e.getMessage());
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取当前apk的版本名
     *
     * @param context 上下文
     * @return
     */
    public static String getVersionName(Context context) {
        String versionName = "";
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionName
            versionName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 比较两个版本号的函数。
     *
     * @param currentVersion 当前版本号字符串
     * @param latestVersion  最新版本号字符串
     * @return 如果需要升级则返回true，否则返回false
     */
    public static boolean compareVersion(String currentVersion, String latestVersion) {
        Log.i("d8g", "compareVersion(current:latest): " + currentVersion + "::::::" + latestVersion);
        // 如果任一版本号为空，则返回false
        if (currentVersion == null || latestVersion == null) {
            return false;
        }
        try {
            // 分割版本号字符串
            String[] currentParts = currentVersion.split("\\.");
            String[] latestParts = latestVersion.split("\\.");
            int maxLength = Math.max(currentParts.length, latestParts.length);
            int[] currentVer = new int[maxLength];
            int[] latestVer = new int[maxLength];
            Arrays.fill(currentVer, 0);
            Arrays.fill(latestVer, 0);
            for (int i = 0; i < maxLength; i++) {
                currentVer[i] = i < currentParts.length ? Integer.parseInt(currentParts[i]) : 0;
                latestVer[i] = i < latestParts.length ? Integer.parseInt(latestParts[i]) : 0;
            }
            for (int i = 0; i < maxLength; i++) {
                if (currentVer[i] < latestVer[i])
                    return true;
            }
            return false;
        } catch (NumberFormatException | NullPointerException | ArrayIndexOutOfBoundsException ex) {
            // 捕获异常，返回false
            Log.e("d8g", "version cmp error!" + ex.getMessage());
            return false;
        }
    }


}